package com.bsdsma.visonManagementSystemapp.cos;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.CIUploadResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.*;

@Component
public class CosUtils {

    private static final Set<String> IMAGE_SUFFIX_SET = new HashSet<>(Arrays.asList(".jpg", ".jpeg", ".png", ".gif"));

    @Value("${cos.secret-id}")
    private String secretId;
    @Value("${cos.secret-key}")
    private String secretKey;
    @Value("${cos.region}")
    private String region;
    @Value("${cos.public-bucket.name}")
    private String publicBucketName;
    @Value("${cos.public-bucket.domain}")
    private String publicBucketDomain;

    private COSClient client = null;

    private COSClient getClient(){
        if(null == client){
            COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
            Region regionConfig = new Region(region);
            ClientConfig clientConfig = new ClientConfig(regionConfig);
            clientConfig.setHttpProtocol(HttpProtocol.https);
            client = new COSClient(cred, clientConfig);
        }
        return client;
    }

    /**
     * 文件上传
     * @param key   指定文件上传到 COS 上的路径，即对象键。例如对象键为folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
     * @param file  上传的文件
     * @param pub   是否上传到公共bucket上 false则上传到私有bucket上
     */
    public CosUploadDTO upload(String key, File file){
        CosUploadDTO ret = new CosUploadDTO();
        PutObjectRequest putObjectRequest = new PutObjectRequest(publicBucketName, key, file);
        if(isImage(key)){
            PicOperations picOperations = new PicOperations();
            // 是否返回原图信息，0不返回原图信息，1返回原图信息，默认为0
            picOperations.setIsPicInfo(1);
            // 添加图片处理规则
            List<PicOperations.Rule> ruleList = new LinkedList<>();
            PicOperations.Rule rule1 = new PicOperations.Rule();
            rule1.setBucket(publicBucketName);
            rule1.setFileId(formatWebpFileId(key));
            rule1.setRule("imageMogr2/format/webp");
            ruleList.add(rule1);
            picOperations.setRules(ruleList);
            putObjectRequest.setPicOperations(picOperations);
        }
        PutObjectResult putObjectResult = getClient().putObject(putObjectRequest);
        String requestId = putObjectResult.getRequestId();
        ret.setRequestId(requestId);
        ret.setKey(key);
        ret.setLocation(publicBucketDomain + key);
        CIUploadResult ciUploadResult = putObjectResult.getCiUploadResult();
        if(null != ciUploadResult){
            String originalLocation = ciUploadResult.getOriginalInfo().getLocation();
            ret.setOriginalLocation("https://" + originalLocation);
            ProcessResults processResults = ciUploadResult.getProcessResults();
            if(null != processResults){
                List<CIObject> objectList = processResults.getObjectList();
                if(!CollectionUtils.isEmpty(objectList)){
                    CIObject ciObject = objectList.get(0);
                    String compressKey = ciObject.getKey();
                    String compressLocation = ciObject.getLocation();
                    ret.setCompressLocation("https://" + compressLocation);
                    ret.setCompressKey(compressKey);
                }
            }
        }
        return ret;
    }

    /**
     * 获取文件名 去掉路径
     * @return  文件名
     */
    private String getFilename(String key){
        return key.substring(key.lastIndexOf("/") + 1);
    }

    /**
     * 将Key转换为Webp Key
     */
    public String formatWebpFileId(String key){
        String filename = getFilename(key);
        return "webp_" + filename;
    }

    /**
     * 判断key是否为图片
     */
    private boolean isImage(String key){
        String suffix = key.substring(key.lastIndexOf("."));
        return IMAGE_SUFFIX_SET.contains(suffix.toLowerCase());
    }

    public String getPublicBucketDomain() {
        return publicBucketDomain;
    }

}
